package de.g18.scavengerhunt.activity;

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import de.g18.scavengerhunt.AppApplicationContext;
import de.g18.scavengerhunt.R;
import de.g18.scavengerhunt.types.DatabaseAdapter;
import de.g18.scavengerhunt.types.DownloadImageTask;
import de.g18.scavengerhunt.utils.GameUtils;
import de.g18.scavengerhunt.utils.ImageUtils;
import de.g18.scavengerhunt.utils.WebserviceUtil;

/**
 *  This is the settings acitivty, to select user name and picture
 */
public class SettingsActivity extends Activity {

    private DatabaseAdapter      databaseAdapter     = null;

    private WebserviceUtil       webserviceUtil      = null;

    private static final int   SELECT_PICTURE      = 1;

    private Bitmap               choosenProfileImage = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        databaseAdapter = new DatabaseAdapter(this);
        webserviceUtil = WebserviceUtil.getInstance();
        webserviceUtil.setContext(this);
        webserviceUtil.handleUserRegistration();

        final EditText txtUsername = (EditText) findViewById(R.id.txtUsername);
        if (AppApplicationContext.getUser() != null) {
            txtUsername.setText(AppApplicationContext.getUser().getName());
        } else {
            txtUsername.setText(databaseAdapter.getUserName());
        }

        ImageView imageView = (ImageView) findViewById(R.id.imgProfilePictureView);
        String encodedImage = databaseAdapter.getEncodedImage();
        if (encodedImage.length() > 0) {
            imageView.setImageBitmap(ImageUtils.getBitmapFromBase64(encodedImage));
        } else {
            String receiveEncodedProfileImage = webserviceUtil.receiveEncodedProfileImage(AppApplicationContext.getUser().getId());
            imageView.setImageBitmap(ImageUtils.getBitmapFromBase64(receiveEncodedProfileImage));
        }

        Button btnSave = (Button) findViewById(R.id.btnSave);
        Button btnLoadImage = (Button) findViewById(R.id.btnLoadPicture);
        btnSave.setOnClickListener(getBtnSaveListener(txtUsername));
        btnLoadImage.setOnClickListener(getBtnLoadImageListener());
    }

    /**
     * Returns string path to URI.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        if (resultCode == RESULT_OK && imageReturnedIntent != null) {
            if (requestCode == SELECT_PICTURE) {
                Bitmap selectedImage = null;
                Uri selectedImageUri = imageReturnedIntent.getData();
                final String[] filePathColumn = {MediaColumns.DATA, MediaColumns.DISPLAY_NAME};
                Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);

                // Some devices (dependent on OS version) return an URI of com.android instead of com.google.android
                if (selectedImageUri.toString().startsWith("content://com.android.gallery3d.provider")) {
                    // Use the com.google provider.
                    selectedImageUri = Uri.parse(selectedImageUri.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
                }
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(MediaColumns.DATA);

                    // If it is a picasa image on newer devices with OS 3.0 and up
                    if (selectedImageUri.toString().contains("com.google.android.gallery3d")) {
                        columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);
                        if (columnIndex != -1) {
                            // TODO Here we can implement a progress bar and set it visible to show the download status.
                            try {
                                selectedImage = new DownloadImageTask().execute(cursor.getString(columnIndex), selectedImageUri).get();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        // It is a regular local image file
                        String filePath = cursor.getString(columnIndex);
                        cursor.close();
                        selectedImage = BitmapFactory.decodeFile(filePath);
                    }
                }
                // TODO Implement support for picasa images on devices running OS 3.0 or prior.

                ImageView imageView = (ImageView) findViewById(R.id.imgProfilePictureView);
                if (selectedImage != null) {
                    choosenProfileImage = ImageUtils.getResizedBitmap(selectedImage, 100, 100);
                    imageView.setImageBitmap(choosenProfileImage);
                }
            }
        }
    }

    /**
     * Returns OnClickListener which handles btnLoadImage actions.
     */
    private OnClickListener getBtnLoadImageListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Profilbild festlegen"), SELECT_PICTURE);
            }
        };
    }

    /**
     * Returns OnClickListener which handles btnSave actions.
     */
    private OnClickListener getBtnSaveListener(final EditText txtUsername) {
        return new OnClickListener() {
            @Override
            public void onClick(View view) {
                String newUsername = txtUsername.getText().toString().trim();
                if (!databaseAdapter.getUserName().equals(newUsername) && !newUsername.equals("")) {
                    // Rename user in webservice and database:
                    if (webserviceUtil.setUserName(AppApplicationContext.getUser().getId(), newUsername)) {
                        databaseAdapter.setUserName(newUsername);
                    }
                }

                String encodedImage = ImageUtils.encodeImageBase64(choosenProfileImage);
                if (!databaseAdapter.getEncodedImage().equals(encodedImage)) {
                    int userId = AppApplicationContext.getUser().getId();
                    if (webserviceUtil.uploadProfileImage(userId, encodedImage)) {
                        databaseAdapter.setEncodedImage(encodedImage);
                    }
                }

                GameUtils.showActivity(new MainMenuActivity());
            }
        };
    }

    /**
     * Called automatically when the Activity has been created and will be visible to the user.
     */
    @Override
    protected void onStart() {
        super.onStart();

        // Give the ApplicationContext the current activity instance.
        AppApplicationContext.setActivity(this);
    }

    /**
     * This override makes sure, that the device back button only intents to load the MainMenuActivity.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            GameUtils.showActivity(new MainMenuActivity());
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }
}
